package cn.edu.scau.cmi.wujiaxian.singleton;

import java.util.HashMap;
import java.util.Map;

/**
   *  多例模式实验
 *
 * @author
 *
 */
public class Marshal {
	
	/**
	 * 多例数量
	 */
	private static final int N = 10;
	
	/**
	 * 存放N个实例对象的容器
	 */
	private static Map<String, Marshal> marshalMap = new HashMap<>(N);
	
	/**
	 * 名字
	 */
	private String name;

	/**
	 * 私有构造方法 防止外界应用程序实例化
	 * @param name
	 */
	private Marshal(String name) {
		this.name = name;
	}

	/**
	 * 添加实例
	 * @param name
	 * @return
	 */
	public static String addInstance(String name) {
		if (marshalMap.containsKey(name)) {
			return "元帅：" + marshalMap.get(name) + "已经存在";
		}
		
		if (marshalMap.size() >= 10 ) {
			return "只有10个元帅";
		}
		
		Marshal marshal = new Marshal(name);
			
		marshalMap.put(name, marshal);
		return "元帅：" + marshalMap.get(name) + "添加成功";
	}
	
	/**
	 *  获取实例对象
	 */
	public static Marshal getInstance(String name) {
		return marshalMap.get(name);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof Marshal)) {
			return false;
		}
		Marshal marshal = (Marshal) obj;
		return marshal.getName().equals(this.name);
	}
	
	@Override
	public String toString() {
		return name + super.toString();
	}
}
